import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('../views/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('../views/Orders.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/Users.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('../views/Products.vue'),
        meta: { title: '商品管理' }
      },
      {
        path: 'products/add',
        name: 'AddProduct',
        component: () => import('../views/AddProduct.vue'),
        meta: { title: '添加商品' }
      },
      {
        path: 'system',
        name: 'System',
        component: () => import('../views/System.vue'),
        meta: { title: '系统管理' }
      },
      {
        path: 'system/add-admin',
        name: 'AddAdmin',
        component: () => import('../views/AddAdmin.vue'),
        meta: { title: '添加管理员' }
      },
      {
        path: 'group-buying',
        name: 'GroupBuying',
        component: () => import('../views/GroupBuying.vue'),
        meta: { title: '待拼团列表' }
      }
    ]
  },
  {
    path: '/change-password',
    name: 'ChangePassword',
    component: () => import('../views/ChangePassword.vue'),
    meta: {
      requiresAuth: true,
      title: '修改密码'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
 
  const token = localStorage.getItem('token')

  if (to.meta.requiresAuth && !token) {
   
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else if (to.path === '/login' && token) {
   
    next({ path: '/' })
  } else {
    next()
  }
})

export default router 